//
//  ManagerEngine.m
//  BeiBeiDemo
//
//  Created by mac on 16/2/22.
//  Copyright (c) 2016年 mac. All rights reserved.
//

#import "ManagerEngine.h"
#import "MyViewController.h"
#import "DetailViewController.h"
#import "VipViewController.h"

static UILabel *alertLabel ;


@class HomeViewController;
@class NearViewController;
@class BusinessDeterminedViewController;
@class MyViewController;

static const CGFloat  sAlertTimer = 3.0;
@implementation ManagerEngine
-(instancetype)init {
    self = [super init];
    if (self) {
        
    }
   
    return self;
}
+(void)GoMainView
{
    
    
#pragma mark -----我的
    
    
    
    MyViewController *MyVc = [[MyViewController alloc]init];//--个人信息
    
    UIImage *MyImage = [UIImage imageNamed:@"wode_normal"];
    
    UIImage *MyImageS = [[UIImage imageNamed:@"wode_selected"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    
    MyVc.tabBarItem = [[UITabBarItem alloc]initWithTitle:@"我的" image:MyImage selectedImage:MyImageS];
    
    
    
    ZWNavigationController *MyNav = [[ZWNavigationController alloc]initWithRootViewController:MyVc];
    
    
    [MyNav.tabBarItem setTitlePositionAdjustment:UIOffsetMake(0, -4)];
    [[UITabBar appearance]setTintColor:[self getColor:@"00ccb8"]];

    
    
#pragma mark -----会员
    
    VipViewController *VipVc = [[VipViewController alloc]init];
    
    UIImage *mainImage = [UIImage imageNamed:@"huiyuan_normal"];
    
    UIImage *mainImageS = [[UIImage imageNamed:@"huiyuan_selected"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    

    VipVc.tabBarItem = [[UITabBarItem alloc]initWithTitle:@"会员" image:mainImage selectedImage:mainImageS];
    

    ZWNavigationController *VipNvc =[[ZWNavigationController alloc]initWithRootViewController:VipVc];
    
    [VipNvc.tabBarItem setTitlePositionAdjustment:UIOffsetMake(0, -4)];
//    [[UITabBar appearance]setTintColor:[self getColor:@"00ccb8"]];



    
#pragma mark -----明细
    
    DetailViewController *DetailVc = [[DetailViewController alloc]init];
    
    UIImage *DetailImage = [UIImage imageNamed:@"mingxi_normal"];
    
    UIImage *DetailImageS = [[UIImage imageNamed:@"mingxi_selected"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    DetailVc.tabBarItem = [[UITabBarItem alloc]initWithTitle:@"明细" image:DetailImage selectedImage:DetailImageS];
    
    
      ZWNavigationController *DetailNav = [[ZWNavigationController alloc]initWithRootViewController:DetailVc];
    [DetailNav.tabBarItem setTitlePositionAdjustment:UIOffsetMake(0, -4)];
//    [[UITabBar appearance]setTintColor:[self getColor:@"00ccb8"]];


    
#pragma mark ----选择
    
    UITabBarController *tabbars = [[UITabBarController alloc]init];
    

    
    tabbars.viewControllers = @[MyNav,VipNvc,DetailNav];

    
    [[UIApplication sharedApplication].delegate.window setRootViewController:tabbars];
    
    UIView *backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 420, 49)];
    
    backView.backgroundColor = [UIColor whiteColor];
    

//    [[UITabBar appearance]setTintColor:[self getColor:@"00ccb8"]];

//     [self titleColor];
    
    tabbars.tabBar.opaque = YES;

 
}

+(void)titleColor
{
    [[UITabBar appearance]setTintColor:[self getColor:@"00ccb8"]];

}

#pragma mark-----16进制颜色值转换
+ (UIColor *)getColor:(NSString *)hexColor
{
    unsigned int red,green,blue;
    
    NSRange range;
    
    range.length = 2;
    
    range.location = 0;
    
    [[NSScanner localizedScannerWithString:[hexColor substringWithRange:range]]scanHexInt:&red];
    
    range.location = 2;
    
    [[NSScanner localizedScannerWithString:[hexColor substringWithRange:range]]scanHexInt:&green];

     range.location = 4;
    
    [[NSScanner localizedScannerWithString:[hexColor substringWithRange:range]]scanHexInt:&blue];

    return [UIColor colorWithRed:(float)(red/255.0f) green:(float)(green/255.0f) blue:(float)(blue/255.0f) alpha:1.0f];
}

#pragma mark --
#pragma mark ---颜色转图片
+ (UIImage *)createImageWithColor:(UIColor *)color
{
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return theImage;
}



#pragma mark --
#pragma mark ---提醒动画
+(void)homeSvpStr:(NSString *)tit andcenterView:(UIView *)view andStyle:(promptViewStyle)type {
    
        [self dismissHomeSvP];
        alertLabel = [[UILabel alloc]init];
        alertLabel.text = tit;
        alertLabel.font = [UIFont systemFontOfSize:12];
        alertLabel.numberOfLines = 0;
        alertLabel.textAlignment = NSTextAlignmentCenter;
        alertLabel.alpha = 0;
        [view addSubview:alertLabel];
    
        CGFloat  timers =  tit.length *0.15f ; // 延迟消失时间
    
    
  
    if (type == promptViewDefault) {
        alertLabel.frame = CGRectMake(0, 0, WIDTH, 30);
        alertLabel.backgroundColor = [UIColor whiteColor];
        [UIView animateWithDuration:1 animations:^{
            alertLabel.alpha = 1;
            alertLabel.frame = CGRectMake(0, 64, WIDTH, 30);
            
        } completion:^(BOOL finished) {
            dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.0/*延迟执行时间*/ * NSEC_PER_SEC));
            
            dispatch_after(delayTime, dispatch_get_main_queue(), ^{

                
                [UIView animateWithDuration:1 delay:timers options:UIViewAnimationOptionLayoutSubviews animations:^{
                    alertLabel.frame = CGRectMake(0, 0, WIDTH, 0);

                } completion:^(BOOL finished) {
                    alertLabel.alpha = 0;
                    [self dismissHomeSvP];
                }];
                

            });
                                                    
            
        }];
    } else if (type == promptViewFadeAway){
        alertLabel.center = CGPointMake(view.center.x,HEIGHT/4*2 );
        alertLabel.bounds = CGRectMake(0, 0, tit.length*12.5+5*2, 30);
        alertLabel.layer.masksToBounds = YES;
        
        alertLabel.layer.cornerRadius = 3;
        
        alertLabel.textAlignment = NSTextAlignmentCenter;
        alertLabel.backgroundColor = [UIColor blackColor];
        
        alertLabel.textColor = [UIColor whiteColor];
        
        [UIView animateWithDuration:sAlertTimer animations:^{
            alertLabel.alpha = 1;
            
        } completion:^(BOOL finished) {
            
            
            [UIView animateWithDuration:sAlertTimer animations:^{
                alertLabel.alpha = 0;

            } completion:^(BOOL finished) {
                [self dismissHomeSvP];
            }];
            
        }];
        
    } else {
        
        alertLabel = nil;
        
    }

    
    
}
+(void)dismissHomeSvP {
    
    [alertLabel removeFromSuperview];
    
    
}

#pragma mark -----网络状态
+(void)networkStatus
{
     static NSString *typ;
    // 1.获得网络监控的管理者
    AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
    
    // 2.设置网络状态改变后的处理
    [mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        // 当网络状态改变了, 就会调用这个block
      
        switch (status) {
            case AFNetworkReachabilityStatusUnknown: // 未知网络
                typ =UnknownNetwork;
                break;
                
            case AFNetworkReachabilityStatusNotReachable: // 没有网络(断网)
                typ =NoInternet;

                break;
                
            case AFNetworkReachabilityStatusReachableViaWWAN: // 手机自带网络
                typ =WWANInternet;
                
                break;
                
            case AFNetworkReachabilityStatusReachableViaWiFi: // WIFI
                typ =WIFIInternet;
                break ;
        }
        [[NSNotificationCenter defaultCenter]postNotificationName:NetworkStatus object:nil userInfo:@{@"IAmaNetwork":typ}];

    }];
    [mgr startMonitoring];
}

#pragma mark ---从状态栏获取当前网络状态
+(NSInteger)statusBarNetWork {
    
    // 状态栏是由当前app控制的，首先获取当前app
    UIApplication *app = [UIApplication sharedApplication];
    
    NSArray *children = [[[app valueForKeyPath:@"statusBar"] valueForKeyPath:@"foregroundView"] subviews];
    
    NSInteger type = 0;
    /**
     *  ：0 - 无网络; 1 - 2G; 2 - 3G; 3 - 4G; 5 - WIFI
     */
    for (id child in children) {
        if ([child isKindOfClass:NSClassFromString(@"UIStatusBarDataNetworkItemView")]) {
            type = [[child valueForKeyPath:@"dataNetworkType"] intValue];
        }
    }
    
    NSLog(@"----%ld",(long)type);
    
    return type;
    
}
+(CGFloat)setTextWidthStr:(NSString *)str andFont:(UIFont *)fonts {
    
    CGRect frame = [str boundingRectWithSize:CGSizeMake(1000, 1000)options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: fonts} context:nil];
    
    
    return frame.size.width;
}
#pragma mark ----时间戳
+ (NSDate *)getInternetDate
{
    
    NSString *urlString = @"http://m.baidu.com/";
    
    urlString = [urlString stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
    
    // 实例化NSMutableURLRequest，并进行参数配置
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    
    [request setURL:[NSURL URLWithString: urlString]];
    
    [request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
    
    [request setTimeoutInterval: 5];
    
    [request setHTTPShouldHandleCookies:FALSE];
    
    [request setHTTPMethod:@"GET"];
    
    NSError *error = nil;
    
    NSHTTPURLResponse *response;
    
    [NSURLConnection sendSynchronousRequest:request
     
                          returningResponse:&response error:&error];
    if (error) {
        return [NSDate date];
    }
    
    //    NSLog(@"response is %@",response);
    
    NSString *date = [[response allHeaderFields] objectForKey:@"Date"];
    //    NSLog(@"date is \n%@",date);
    
    date = [date substringFromIndex:5];
    
    date = [date substringToIndex:[date length]-4];
    
    NSDateFormatter *dMatter = [[NSDateFormatter alloc] init];
    
    dMatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
    
    [dMatter setDateFormat:@"dd MMM yyyy HH:mm:ss"];
    
    [dMatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:8]];//直接指定时区，这里是东8区
    
    
    NSDate *netDate = [[dMatter dateFromString:date] dateByAddingTimeInterval:60*60*8];
    
    return netDate;
    
}


#pragma mark - base64
//+ (NSString*)encodeBase64String:(NSString * )input {
//    NSData *data = [input dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
//    data = [GTMBase64 encodeData:data];
//    NSString *base64String = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//    return base64String;
//}
//
//+ (NSString*)decodeBase64String:(NSString * )input {
//    NSData *data = [input dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
//    data = [GTMBase64 decodeData:data];
//    NSString *base64String = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//    return base64String;
//}
//
//+ (NSString*)encodeBase64Data:(NSData *)data {
//    data = [GTMBase64 encodeData:data];
//    NSString *base64String = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//    return base64String;
//}
//
//+ (NSString*)decodeBase64Data:(NSData *)data {
//    data = [GTMBase64 decodeData:data];
//    NSString *base64String = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//    return base64String;
//}
//
//+ (void)navColorStyle:(UIViewController *)viewController {
//    
//    [viewController.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
//    [viewController.navigationController.navigationBar lt_reset];
//    viewController.navigationController.navigationBar.barTintColor = [ManagerEngine getColor:@"ef2815"];
//    
//}

+ (void)navUnColorStyle:(UIViewController *)viewController {

    [viewController.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
    [viewController.navigationController.navigationBar setShadowImage:[UIImage new]];
}

//设置不同字体颜色
+(void)setTextColor:(UILabel *)label FontNumber:(id)font AndRange:(NSString *)rag AndColor:(UIColor *)vaColor
{
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:label.text];
    //设置字号
    NSRange range = [label.text rangeOfString:rag];
    [str addAttribute:NSFontAttributeName value:font range:range];
    //设置文字颜色
    [str addAttribute:NSForegroundColorAttributeName value:vaColor range:range];
    
    label.attributedText = str;
}


#pragma mark --
#pragma mark ---判断名称是否合法
+ (BOOL)isNameValid:(NSString *)name
{
    BOOL isValid = NO;
    
    if (name.length <=4&&name.length>1)
    {
        for (NSInteger i=0; i<name.length; i++)
        {
            unichar chr = [name characterAtIndex:i];
            
            if (chr < 0x80)
            { //字符
                if (chr >= 'a' && chr <= 'z')
                {
                    isValid = NO;
                }
                else if (chr >= 'A' && chr <= 'Z')
                {
                    isValid = NO;
                }
                else if (chr >= '0' && chr <= '9')
                {
                    isValid = NO;
                }
                else if (chr == '-' || chr == '_')
                {
                    isValid = NO;
                }
                else
                {
                    isValid = NO;
                }
            }
            else if (chr >= 0x4e00 && chr < 0x9fa5)
            { //中文
                isValid = YES;
            }
            else
            { //无效字符
                isValid = NO;
            }
            
            if (!isValid)
            {
                break;
            }
        }
    }
    
    return isValid;
}

#pragma mark --
#pragma mark ---身份证号
+ (BOOL) validateIdentityCard: (NSString *)identityCard
{
    BOOL flag;
    if (identityCard.length <= 0) {
        flag = NO;
        return flag;
    }
    NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    return [identityCardPredicate evaluateWithObject:identityCard];
}

#pragma mark --
#pragma mark ---判断手机号码格式是否正确
+ (BOOL)valiMobile:(NSString *)mobile

{
    
    mobile = [mobile stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    if (mobile.length != 11)
        
    {
        
        return NO;
        
    }else{
        
        /**
         
         * 移动号段正则表达式
         
         */
        
        NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
        
        /**
         
         * 联通号段正则表达式
         
         */
        
        NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
        
        /**
         
         * 电信号段正则表达式
         
         */
        
        NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
        
        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
        
        BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
        
        NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
        
        BOOL isMatch2 = [pred2 evaluateWithObject:mobile];
        
        NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
        
        BOOL isMatch3 = [pred3 evaluateWithObject:mobile];
        
        
        
        if (isMatch1 || isMatch2 || isMatch3) {
            
            return YES;
            
        }else{
            
            return NO;
            
        }
        
    }
    
}

#pragma mark --
#pragma mark ---判断邮箱
+ (BOOL) validateEmail:(NSString *)email
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}


+(void)customAlert:(NSString *)str andViewController:(UIViewController *)selfController isBack:(BOOL)back {
    
    AlertViewController * alert = [AlertViewController alertControllerWithTitle:@"提示" message:str];
    if (back) {
        [alert addAction:[AlertAction actionWithTitle:@"确定" handler:^(AlertAction *action) {
            [[NSNotificationCenter defaultCenter]postNotificationName:@"changeBonus" object:nil];
            [selfController.navigationController popViewControllerAnimated:YES];
        } ]];
    } else {
        [alert addAction:[AlertAction actionWithTitle:@"确定" handler:nil]];
    }
   
    [selfController presentViewController:alert animated:YES completion:nil];
    
    
    
    
}

@end
